<template>
  <el-dialog
    title="配置权限"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <!-- TODO 父子选中状态问题 -->
    <el-tree
      ref="tree"
      show-checkbox
      :data="treeData"
      :props="treeProps"
      node-key="id"
      :check-strictly="true"
      :default-checked-keys="defaultChecked"
    ></el-tree>

    <!-- 保存按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="save" :loading="loading"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
// api
import sysApi from "@/api/sysApi";

export default {
  name: "sysRolePermission",
  data() {
    return {
      dialogVisible: false,
      
      // 保存按钮加载状态
      loading: false,

      // 角色ID
      roleId: null,

      // 默认选中菜单
      defaultChecked: [],
      treeProps: {
        children: "children",
        label: "name",
      },

      // 菜单列表数据
      treeData: [],
    };
  },
  methods: {
    // 请求数据
    remoteData() {
      sysApi.sysPermission
        .treeList()
        .then((permissionResult) => {
          sysApi.sysRole
            .rolePermissionIds(this.roleId)
            .then((rolePermissionResult) => {
              this.treeData = permissionResult.data;
              this.$nextTick(() => {
                this.expandAll();
                this.setChecked(rolePermissionResult.data);
              });
            })
            .catch((error) => {});
        })
        .catch((error) => {});
    },
    // 全部展开
    expandAll() {
      for (var i in this.$refs.tree.store.nodesMap) {
        this.$refs.tree.store.nodesMap[i].expanded = true;
      }
    },
    // 设置选中
    setChecked(checkedData) {
      for (var i in this.$refs.tree.store.nodesMap) {
        this.$refs.tree.store.nodesMap[i].checked = false;
      }
      this.defaultChecked = checkedData;
    },
    // 打开弹框
    open(row) {
      this.roleId = row.id;
      this.remoteData();
      this.dialogVisible = true;
      this.loading = false;
    },
    // 保存角色权限
    save() {
      this.loading = true;
      sysApi.sysRole
        .updateRolePermission(this.$refs.tree.getCheckedKeys(), this.roleId)
        .then((res) => {
          this.$message.success({
            message: "关联成功",
            duration: 1000,
            onClose: () => {
              this.dialogVisible = false;
            },
          });
        })
        .catch((error) => {
          this.loading = false;
        });
    },
  },
};
</script>